package com.atguigu.day03;

import com.atguigu.bean.Event;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Flink12_Transform_RichFun {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //TODO 3.将读进来的字符串转为Event
        SingleOutputStreamOperator<Event> map = streamSource.map(
                //使用富函数
                new MyRichMap()
//                new MapFunction<String, Event>() {
//            @Override
//            public Event map(String value) throws Exception {
//                String[] split = value.split(",");
//                return new Event(split[0], split[1], Long.parseLong(split[2]));
//            }
//        }

        );


        map.print();

        env.execute();
    }

    public static class MyRichMap extends RichMapFunction<String, Event> {
        /**
         * 生命周期方法初始化方法  比如创建链接
         * 在调用这个算子之前最先被调用
         * 在每个并行度上调用一次
         * @param parameters The configuration containing the parameters attached to the contract.
         * @throws Exception
         */
        @Override
        public void open(Configuration parameters) throws Exception {
            //获取运行时上下文对象
            System.out.println(getRuntimeContext().getJobId());
            System.out.println("open........");
        }

        /**
         * 生命周期方法 清理方法 比如释放资源
         * 在调用这个算子之后被调用
         * 在每个并行度上调用一次
         * @throws Exception
         */
        @Override
        public void close() throws Exception {
            System.out.println("close......");
        }

        @Override
        public Event map(String value) throws Exception {
            String[] split = value.split(",");
            return new Event(split[0], split[1], Long.parseLong(split[2]));
        }
    }
}
